import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Decription 直接内存溢出
 * -Xmx20M -XX:MaxDirectMemorySize=10M
 * Date 2017/10/6 19:31
 * authur MangoDai
 **/
public class DirectMemoryOOM {
    private static final int _1MB = 1 << 20; // 1M

    /**
     * Exception in thread "main" java.lang.OutOfMemoryError
     at sun.misc.Unsafe.allocateMemory(Native Method)
     at DirectMemoryOOM.main(DirectMemoryOOM.java:19)
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe) unsafeField.get(null);
        while (true) {
            unsafe.allocateMemory(_1MB);
        }
    }
}
